<template>
  <div>
    <Drawer
      title="分配权限"
      :value="showModal"
      width="20%"
      :mask-closable="false"
      :styles="styles"
      @on-close="changeVisible(false)">
      <a-tree
        v-model="selectedPermissions"
        showLine
        checkable
        multiple
        :defaultExpandParent="autoExpandParent"
        :replaceFields="replaceFields"
        :treeData="permissionData"
      />
      <div class="permission-drawer-footer">
        <Button style="margin-right: 8px" @click="changeVisible(false)">取消</Button>
        <Button type="primary" @click="handleSubmit()">提交</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>

  import 'ant-design-vue/dist/antd.css'
  import aTree from 'ant-design-vue/lib/tree'
  import {getPermissions} from '@/api/role'

  export default {
    name: 'role-permission',
    components: {
      aTree
    },
    props: {
      showModal: {
        type: Boolean,
        default: false
      },
      roleId: {
        type: Number | String,
        default: 0
      },
      permissionData: {
        type: Array,
        default() {
          return []
        }
      },
    },
    watch: {
      roleId: function (id) {
        if (id) {
          getPermissions({id: id}).then(res => {
            this.selectedPermissions = res.data
          })
        }
      },
    },
    data() {
      return {
        autoExpandParent: true,
        replaceFields: {
          children: 'child',
          title: 'display_name',
          key: 'id'
        },
        selectedPermissions: [],
        styles: {
          height: 'calc(100% - 55px)',
          overflow: 'auto',
          paddingBottom: '53px',
          position: 'static'
        },
      }
    },
    methods: {
      handleGetPermissions: function (roleId) {
        if (roleId) {
          getPermissions({id: roleId}).then(res => {
            this.selectedPermissions = res.data
          })
        }
      },
      handleSubmit() {
        this.$emit('handleSubmit', {
          id: this.roleId,
          permissions: this.selectedPermissions
        })
      },
      changeVisible: function (val) {
        this.$emit('changeVisible', val)
      },
    }
  }
</script>

<style scoped>
  .permission-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
</style>
